package top.zhanglingxi.controller;

import lombok.NonNull;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.zhanglingxi.algorithms.BFS;
import top.zhanglingxi.algorithms.Labyrinth;
import top.zhanglingxi.algorithms.Point;
import top.zhanglingxi.algorithms.ShortestPath;
import top.zhanglingxi.domain.req.CalcShortestPathReq;
import top.zhanglingxi.enums.PointEnum;

import java.util.HashMap;
import java.util.Map;

/**
 * 计算迷宫最短路径Controller
 * @author ZWX
 */
@RestController
@RequestMapping("/calc/shortest/path")
public class CalcShortestPathController {

    /**
     * 计算迷宫最短路径
     * @param req 请求参数
     * @return 迷宫最短路径
     */
    @PostMapping
    public Map<String, Object> calcShortestPath(@RequestBody CalcShortestPathReq req) {
        Labyrinth labyrinth = GenerateLabyrinthController.labyrinth;
        @NonNull Point[][] points = labyrinth.getPoints();
        // 设置起点和终点
        points[req.getStart().getX()][req.getStart().getY()].setType(PointEnum.RED);
        labyrinth.setStart(points[req.getStart().getX()][req.getStart().getY()]);
        points[req.getEnd().getX()][req.getEnd().getY()].setType(PointEnum.GREEN);
        labyrinth.setEnd(points[req.getEnd().getX()][req.getEnd().getY()]);
        // 计算迷宫最短路径
        BFS bfs = new BFS();
        ShortestPath shortestPath = bfs.getShortestPath(labyrinth);
        // 返回计算结果
        HashMap<String, Object> res = new HashMap<>(2);
        res.put("code", 200);
        res.put("data", shortestPath);
        // 计算完毕重置迷宫缓存
        points[req.getStart().getX()][req.getStart().getY()].setType(PointEnum.WHITE);
        labyrinth.setStart(null);
        points[req.getEnd().getX()][req.getEnd().getY()].setType(PointEnum.WHITE);
        labyrinth.setEnd(null);
        return res;
    }

}
